#include "myplaimtextedit.h"
#include <QDebug>
#include <QScrollBar>

MyPlaimTextEdit::MyPlaimTextEdit(QWidget *parent):QPlainTextEdit(parent)
{
    initTimer();
    auto s = this->verticalScrollBar();
    if(s){
        s->setMinimumHeight(120);
        s->installEventFilter(this);
    }else{
        qDebug()<<__FUNCTION__;
    }
}

void MyPlaimTextEdit::initTimer()
{
    auto checkStatusFunc = [this](){
        static bool lastStatus = false;
        if(onOperation == false && isPress == false){
            if(lastStatus == false){
                this->moveCursor(QTextCursor::End);
                isAuto = true;
                return;
            }
        }
        lastStatus = onOperation;
        onOperation = false;
        isAuto = false;
    };

//    auto testTimer = new QTimer(this);
//    testTimer->callOnTimeout([this](){this->appendPlainText("中文测试");});
//    testTimer->start(500);

    connect(&timer,&QTimer::timeout,[checkStatusFunc](){checkStatusFunc();});
    timer.start(1000);

    connect(this,&MyPlaimTextEdit::textChanged,[this](){
        if(isAuto){
            this->moveCursor(QTextCursor::End);
        }
    });
}


void MyPlaimTextEdit::mouseMoveEvent(QMouseEvent *event)
{
    onOperation = true;
    QPlainTextEdit::mouseMoveEvent(event);
}

void MyPlaimTextEdit::wheelEvent(QWheelEvent *event)
{
    onOperation = true;
    QPlainTextEdit::wheelEvent(event);
}

void MyPlaimTextEdit::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        isPress = true;
        qDebug()<<"isPress = true;";
    }
    QPlainTextEdit::mousePressEvent(event);
}

void MyPlaimTextEdit::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        isPress = false;
        qDebug()<<"isPress = false;";
    }
    QPlainTextEdit::mouseReleaseEvent(event);
}

bool MyPlaimTextEdit::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress)
    {
        isPress = true;
    }

    if(event->type() == QEvent::MouseButtonRelease){
        isPress = false;
    }

    return false;

}
